/*
 * Copyright (C) 2015 备胎金服
 * 未经授权允许不得进行拷贝和修改
 *   http://www.btjf.com/
 */
package com.zhangman.framework;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangman on 2016/11/1 10:25.
 * Email: zhangman523@126.com
 */
public class Pool<T> {
  public interface PoolObjectFactory<T> {
    public T createObject();
  }

  private final List<T> freeObjects;
  private final PoolObjectFactory<T> mFactory;
  private final int mMaxSize;

  public Pool(int maxSize, PoolObjectFactory<T> factory) {
    mMaxSize = maxSize;
    mFactory = factory;
    freeObjects = new ArrayList<>();
  }

  public T newObject() {
    T object = null;
    if (freeObjects.size() == 0) {
      object = mFactory.createObject();
    } else {
      object = freeObjects.remove(freeObjects.size() - 1);
    }
    return object;
  }

  public void free(T object) {
    if (freeObjects.size() < mMaxSize) {
      freeObjects.add(object);
    }
  }
}
